package com.nyist.diseasepreventionserver.config;

import com.nyist.diseasepreventionserver.common.ResponseCode;
import com.nyist.diseasepreventionserver.common.ServerResponse;
import com.nyist.diseasepreventionserver.dto.UserDTO;
import com.nyist.diseasepreventionserver.entity.PowerController;
import com.nyist.diseasepreventionserver.entity.Role;
import com.nyist.diseasepreventionserver.entity.User;
import com.nyist.diseasepreventionserver.service.UserService;
import com.nyist.diseasepreventionserver.util.SpringUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;

import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

import static java.awt.SystemColor.info;


public class MyRealm extends AuthorizingRealm {

    //授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        //获取当前用户
        User user = (User) SecurityUtils.getSubject().getPrincipal();
        List<Role> roles = user.getRoles();
        Set<String> roleName = roles.stream().map(Role::getPowerName).collect(Collectors.toSet());
        //获取当前用户的角色对象
        Role role = roles.get(0); //角色分两种：admin、user
        List<PowerController> powerControllers = role.getPowerControllers();
        Set<String> permissons = powerControllers.stream().map(PowerController::getController).collect(Collectors.toSet());
        info.setRoles(roleName);
        info.setStringPermissions(permissons);
        return info;

    }

    //认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        UsernamePasswordToken usernamePasswordToken = (UsernamePasswordToken) token;
        UserService userService = SpringUtil.getBean(UserService.class);
        Integer userSid = Integer.valueOf(usernamePasswordToken.getUsername());
        UserDTO userDTO = userService.findOne(userSid);
        if (userDTO == null){
            System.out.println("1");
            return null;
        }
        //判断密码
        return  new SimpleAuthenticationInfo(userDTO,userDTO.getUserPassword(),"");
    }
}
